<template>
    <div class="app-container">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
  <el-form-item label="查找的内容">
    <el-input v-model="formInline.content" placeholder="账号|手机|邮箱" size="small"></el-input>
  </el-form-item>
  <el-form-item label="选择">
    <el-select v-model="formInline.sex" placeholder="性别" style="width: 100px;" size="small">
      <el-option label="请选择" value=""></el-option>
      <el-option label="男" value="1"></el-option>
      <el-option label="女" value="0"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="souSuo" size="small" icon="el-icon-search">搜索</el-button>
    <el-button type="success" @click="addDialogForm = true" size="small" icon="el-icon-circle-plus-outline">新增</el-button>
    <!--之前做批量删除功能,已敲好,但使用不起来,把点击事件handleBatchDelete的e删了运行,再重加上运行才能使用 -->
    <!-- 后面摸索到了点解决方法，把修改过的地方ctrl+s 保存一下-->
    <el-button type="danger" @click="handleBatchDelete" size="small" icon="el-icon-remove-outline">批量删除</el-button>
    <el-button type="success" size="small" icon="el-icon-circle-plus-outline">设定角色</el-button>
  </el-form-item>
</el-form>
    <el-table :data="list" style="width: 100%" border height="600" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column prop="id" label="ID" width="50"> </el-table-column>
      <el-table-column prop="loginname" label="账号" width="130">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="100">
      </el-table-column>
      <el-table-column prop="password" label="密码" width="100">
      </el-table-column>
      <el-table-column prop="tel" label="手机" width="150"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="150"> </el-table-column>
      <el-table-column prop="createTime" label="入职日期" width="250">
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="40">
        <template slot-scope="scope">
          {{ scope.row.sex==1?'男':'女' }}
        </template>
      </el-table-column>
      <el-table-column prop="headImg" label="头像" width="200">
      </el-table-column>
      <el-table-column prop="type" label="角色" width="40"> </el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button-group>
            <el-button type="primary" icon="el-icon-edit" @click="updateClick(scope.row)" size="small">修改</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteOne(scope.row)" size="small">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!--添加弹窗-->
    <el-dialog title="添加用户" :visible.sync="addDialogForm" width="30%" center>
  <el-form :model="addForm" :rules="rules2" ref="addForm" label-width="100px">
    <el-form-item label="姓名" prop="username">
      <el-input v-model="addForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="addForm.password"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="password1">
      <el-input v-model="addForm.password1"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="tel">
      <el-input v-model="addForm.tel"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="addForm.email"></el-input>
    </el-form-item>
    <el-form-item label="性别" prop="sex">
      <el-select v-model="addForm.sex" placeholder="请选择">
        <el-option label="请选择" value=""></el-option>
        <el-option label="男" value="1"></el-option>
        <el-option label="女" value="0"></el-option>
      </el-select>
    </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm2('addForm')">立即创建</el-button>
    <el-button @click="resetForm('addForm')">重置</el-button>
  </el-form-item>
  </el-form>
</el-dialog>

    <!--修改框-->
    <el-dialog title="修改用户信息" :visible.sync="updateForm" width="45%" center>
      
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" :inline="true" class="demo-ruleForm">
      <el-form-item label="ID" prop="id">
        <el-input :disabled="true" v-model="ruleForm.id"></el-input>
      </el-form-item>
      <el-form-item label="账号" prop="loginname">
        <el-input :disabled="true" v-model="ruleForm.loginname"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="tel">
        <el-input v-model="ruleForm.tel"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="ruleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="headImg">
        <el-input v-model="ruleForm.headImg"></el-input>
      </el-form-item>
      <el-form-item label="入职日期" prop="createTime">
        <el-input :disabled="true" v-model="ruleForm.createTime"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="type">
        <el-input v-model="ruleForm.type"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="type">
        <el-select v-model="ruleForm.sex" placeholder="请选择">
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="0"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateForm = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    </div>
  </template>
  
  <script>
  import { getList,deleteBatch,addUser,updateUser } from '@/api/user'
  
  export default {
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        list: null,
        listLoading: true,
        total:0,
        currentPage:1,
        pageSize:10,
        addDialogForm: false,
        updateForm:false,
        formInline: {
          content: '',
          sex: ''
        },
        addForm: {
          username: '',
          sex: ''
        },
        rules2: {
          username: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur'}
          ],
          password1: [
            { required: true, message: '请再次输入密码', trigger: 'blur'},
            { validator: this.validatePasswordConfirmation,trigger: 'blur'}
          ],
          tel: [
            { required: true, message: '手机不能为空', trigger: 'change' },
            { pattern: /^1[3456789]\d{9}$/,message: '请输入正确的手机号码',trigger:'blur'}
          ],
          email: [
            { required: true, message: '邮箱不能为空', trigger: 'change' },
            { pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,message: '请输入正确的邮箱地址',trigger:'blur'}
          ],
        },
        selectedRows:[],//定义一个数组用来存放选中的行
        ruleForm: {
          id: '',
          loginname: '',
          username: '',
          password: '',
          tel: '',
          email: '',
          createTime: '',
          sex: '0',
          headImg: '',
          type: '' ,
        },
        rules: {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          password: [
            { required: true, message: '密码不能为空', trigger: 'change' }
          ],
          username: [
            { required: true, message: '用户名不能为空', trigger: 'change' }
          ],
          tel: [
            { required: true, message: '手机不能为空', trigger: 'change' },
            { pattern: /^1[3456789]\d{9}$/,message: '请输入正确的手机号码',trigger:'blur'}
          ],
          email: [
            { required: true, message: '邮箱不能为空', trigger: 'change' },
            { pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,message: '请输入正确的邮箱地址',trigger:'blur'}
          ],
          type: [
            { required: true, message: '角色不能为空', trigger: 'change' }
          ],
          headImg: [
            { required: true, message: '头像不能为空', trigger: 'change' }
          ],
        }
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      //密码确认认证
      validatePasswordConfirmation(rule,value,callback){
        if (value !== this.addForm.password){
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      submitForm2(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            addUser( this.addForm ).then(() => {
            this.$message.success('添加成功');
            this.addDialogForm = false;
            this.fetchData(); // 添加表格数据
          }).catch(error => {
            this.$message.error('失败添加：' + error.message);
          });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            updateUser(this.ruleForm).then(() => {
          this.$message.success('修改成功');
          this.updateForm=false;//关闭对话框
          this.fetchData(); // 刷新表格数据
        }).catch(error => {
          this.$message.error('修改失败：' + error.message);
        });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      onSubmit() {
        console.log('submit!');
      },
      //删除按钮点击事件
      deleteOne(row) {
        this.deleteMethod(row.username,row.id);
      },
        // 批量删除按钮事件处理
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请至少选择一行');
        return;
      }
      var names = this.selectedRows.map(row => row.username);
      var ids = this.selectedRows.map(row => row.id);
      this.deleteMethod(names,ids);
    },

    //分装一个统一的方法供批量删除和表格中的删除按钮公用
    deleteMethod(names,ids){
      
      this.$confirm('确定要删除选中的【'+names+'】用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
         
         console.log("----->"+ids);
        deleteBatch({userids:ids+""}).then(() => {
          this.$message.success('删除成功');
          this.fetchData(); // 刷新表格数据
        }).catch(error => {
          this.$message.error('删除失败：' + error.message);
        });
      }).catch(() => {
        // 用户取消删除
      });
    },
    // 表格行选中事件处理
    handleSelectionChange(rows) {
      this.selectedRows = rows;
    
    },
      souSuo() {
        //调用查询的函数
        this.fetchData();
      },
      fetchData() {
        this.listLoading = true
        getList({currentPage:this.currentPage,pageSize:this.pageSize,content:this.formInline.content,sex:this.formInline.sex}).then(response => {
          this.list = response.data.list
          this.total = response.data.total
          this.listLoading = false
        })
      },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.fetchData();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.fetchData();
    },
    //每一列按钮事件处理
    updateClick(row) {
      this.updateForm = true;
      //将行内的数据显示在表单中
      this.ruleForm.id = row.id;
      this.ruleForm.loginname = row.loginname;
      this.ruleForm.loginname = row.loginname;
      this.ruleForm.username = row.username;
      this.ruleForm.password = row.password;
      this.ruleForm.tel = row.tel;
      this.ruleForm.email = row.email;
      this.ruleForm.createTime = row.createTime;
      this.ruleForm.headImg = row.headImg;
      this.ruleForm.type = row.type;
      this.ruleForm.sex = row.sex;
    }
    }
  }
  </script>
  